#!/bin/bash

# StarRocks MCP Server Kubernetes 部署脚本
# 用于自动化部署 MCP 服务到 Kubernetes 集群

set -e  # 遇到错误时退出

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 日志函数
log_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

log_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 检查必要的工具
check_prerequisites() {
    log_info "检查必要的工具..."
    
    if ! command -v kubectl &> /dev/null; then
        log_error "kubectl 未安装，请先安装 kubectl"
        exit 1
    fi
    
    if ! command -v docker &> /dev/null; then
        log_error "docker 未安装，请先安装 docker"
        exit 1
    fi
    
    log_success "所有必要工具已安装"
}

# 检查 Kubernetes 集群连接
check_k8s_connection() {
    log_info "检查 Kubernetes 集群连接..."
    
    if ! kubectl cluster-info &> /dev/null; then
        log_error "无法连接到 Kubernetes 集群，请检查 kubeconfig 配置"
        exit 1
    fi
    
    log_success "Kubernetes 集群连接正常"
}

# 构建 Docker 镜像
build_image() {
    log_info "构建 Docker 镜像..."
    
    # 获取项目根目录
    PROJECT_ROOT=$(dirname "$(dirname "$(realpath "$0")")")
    
    # 构建镜像
    docker build -t mcp-server-starrocks:latest "$PROJECT_ROOT"
    
    log_success "Docker 镜像构建完成"
}

# 推送镜像到仓库（可选）
push_image() {
    if [ "$PUSH_IMAGE" = "true" ]; then
        log_info "推送镜像到仓库..."
        
        # 请修改为实际的镜像仓库地址
        REGISTRY="your-registry.com"
        IMAGE_NAME="$REGISTRY/mcp-server-starrocks:latest"
        
        docker tag mcp-server-starrocks:latest "$IMAGE_NAME"
        docker push "$IMAGE_NAME"
        
        log_success "镜像推送完成: $IMAGE_NAME"
    fi
}

# 部署到 Kubernetes
deploy_to_k8s() {
    log_info "部署到 Kubernetes..."
    
    # 创建命名空间
    kubectl apply -f namespace.yaml
    
    # 应用所有配置
    kubectl apply -f configmap.yaml
    kubectl apply -f secret.yaml
    kubectl apply -f deployment.yaml
    kubectl apply -f service.yaml
    
    # 可选：应用 Ingress
    if [ "$DEPLOY_INGRESS" = "true" ]; then
        kubectl apply -f ingress.yaml
    fi
    
    log_success "Kubernetes 部署完成"
}

# 等待部署完成
wait_for_deployment() {
    log_info "等待部署完成..."
    
    kubectl wait --for=condition=available --timeout=300s deployment/mcp-server-starrocks -n mcp-starrocks
    
    log_success "部署已完成"
}

# 检查服务状态
check_service_status() {
    log_info "检查服务状态..."
    
    # 检查 Pod 状态
    kubectl get pods -n mcp-starrocks -l app=mcp-server-starrocks
    
    # 检查服务状态
    kubectl get services -n mcp-starrocks
    
    # 检查 Ingress 状态（如果部署了）
    if [ "$DEPLOY_INGRESS" = "true" ]; then
        kubectl get ingress -n mcp-starrocks
    fi
    
    log_success "服务状态检查完成"
}

# 显示访问信息
show_access_info() {
    log_info "服务访问信息："
    
    # 获取服务信息
    SERVICE_IP=$(kubectl get service mcp-server-starrocks-service -n mcp-starrocks -o jsonpath='{.spec.clusterIP}')
    NODEPORT=$(kubectl get service mcp-server-starrocks-nodeport -n mcp-starrocks -o jsonpath='{.spec.ports[0].nodePort}' 2>/dev/null || echo "N/A")
    
    echo ""
    echo "=== 服务访问方式 ==="
    echo "1. 集群内部访问:"
    echo "   http://$SERVICE_IP:8000"
    echo ""
    echo "2. NodePort 访问:"
    if [ "$NODEPORT" != "N/A" ]; then
        echo "   http://<node-ip>:$NODEPORT"
    else
        echo "   NodePort 服务未部署"
    fi
    echo ""
    echo "3. 端口转发访问:"
    echo "   kubectl port-forward service/mcp-server-starrocks-service 8000:8000 -n mcp-starrocks"
    echo "   然后访问: http://localhost:8000"
    echo ""
    echo "4. 健康检查:"
    echo "   curl http://$SERVICE_IP:8000/health"
    echo ""
}

# 清理部署
cleanup() {
    log_info "清理部署..."
    
    kubectl delete -f service.yaml --ignore-not-found=true
    kubectl delete -f deployment.yaml --ignore-not-found=true
    kubectl delete -f secret.yaml --ignore-not-found=true
    kubectl delete -f configmap.yaml --ignore-not-found=true
    kubectl delete -f ingress.yaml --ignore-not-found=true
    kubectl delete -f namespace.yaml --ignore-not-found=true
    
    log_success "清理完成"
}

# 显示帮助信息
show_help() {
    echo "StarRocks MCP Server Kubernetes 部署脚本"
    echo ""
    echo "用法: $0 [选项]"
    echo ""
    echo "选项:"
    echo "  -h, --help              显示帮助信息"
    echo "  -b, --build             构建 Docker 镜像"
    echo "  -p, --push              推送镜像到仓库"
    echo "  -d, --deploy            部署到 Kubernetes"
    echo "  -i, --ingress           部署 Ingress"
    echo "  -c, --cleanup           清理部署"
    echo "  -s, --status            检查服务状态"
    echo "  -a, --all               执行完整部署流程"
    echo ""
    echo "示例:"
    echo "  $0 --all                # 完整部署"
    echo "  $0 --build --deploy     # 构建并部署"
    echo "  $0 --status             # 检查状态"
    echo "  $0 --cleanup            # 清理部署"
}

# 主函数
main() {
    # 默认参数
    BUILD_IMAGE=false
    PUSH_IMAGE=false
    DEPLOY_K8S=false
    DEPLOY_INGRESS=false
    CLEANUP=false
    CHECK_STATUS=false
    SHOW_HELP=false
    
    # 解析命令行参数
    while [[ $# -gt 0 ]]; do
        case $1 in
            -h|--help)
                SHOW_HELP=true
                shift
                ;;
            -b|--build)
                BUILD_IMAGE=true
                shift
                ;;
            -p|--push)
                PUSH_IMAGE=true
                shift
                ;;
            -d|--deploy)
                DEPLOY_K8S=true
                shift
                ;;
            -i|--ingress)
                DEPLOY_INGRESS=true
                shift
                ;;
            -c|--cleanup)
                CLEANUP=true
                shift
                ;;
            -s|--status)
                CHECK_STATUS=true
                shift
                ;;
            -a|--all)
                BUILD_IMAGE=true
                DEPLOY_K8S=true
                DEPLOY_INGRESS=true
                shift
                ;;
            *)
                log_error "未知选项: $1"
                show_help
                exit 1
                ;;
        esac
    done
    
    # 显示帮助信息
    if [ "$SHOW_HELP" = "true" ]; then
        show_help
        exit 0
    fi
    
    # 检查前置条件
    check_prerequisites
    check_k8s_connection
    
    # 执行相应操作
    if [ "$CLEANUP" = "true" ]; then
        cleanup
        exit 0
    fi
    
    if [ "$CHECK_STATUS" = "true" ]; then
        check_service_status
        exit 0
    fi
    
    if [ "$BUILD_IMAGE" = "true" ]; then
        build_image
        push_image
    fi
    
    if [ "$DEPLOY_K8S" = "true" ]; then
        deploy_to_k8s
        wait_for_deployment
        check_service_status
        show_access_info
    fi
    
    log_success "所有操作完成！"
}

# 执行主函数
main "$@"
